﻿using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using Microsoft.Win32; // 用于打开文件/文件夹对话框

namespace WpfApp1
{
    public partial class TreeViewWindow : Window
    {
        public TreeViewWindow()
        {
            InitializeComponent();
        }

        private void OpenFolder_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                dialog.Description = "请选择文件夹";
                dialog.ShowNewFolderButton = false;
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string selectedPath = dialog.SelectedPath;
                    FolderTreeView.Items.Clear();
                    var rootNode = CreateDirectoryNode(new DirectoryInfo(selectedPath));
                    FolderTreeView.Items.Add(rootNode);
                }
            }
        }

        private TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
        {
            var directoryNode = new TreeViewItem
            {
                Header = directoryInfo.Name,
                Tag = directoryInfo.FullName
            };

            // 添加子文件夹
            foreach (var dir in directoryInfo.GetDirectories())
            {
                directoryNode.Items.Add(CreateDirectoryNode(dir));
            }

            // 添加文件
            foreach (var file in directoryInfo.GetFiles())
            {
                var fileNode = new TreeViewItem
                {
                    Header = file.Name,
                    Tag = file.FullName
                };
                directoryNode.Items.Add(fileNode);
            }

            return directoryNode;
        }

        private void FolderTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (FolderTreeView.SelectedItem is TreeViewItem selectedItem)
            {
                string path = selectedItem.Tag as string;
                if (File.Exists(path))
                {
                    try
                    {
                        FileContentTextBox.Text = File.ReadAllText(path);
                    }
                    catch
                    {
                        FileContentTextBox.Text = "无法读取文件内容";
                    }
                }
                else
                {
                    FileContentTextBox.Text = "";
                }
            }
        }
    }
}
